<?php
	set_time_limit(900); //超时时间15分钟

	define('PROXY', 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
	define('CACHE', './proxy/cache/');
	define('CONFIG', './proxy/conf/');

	$url = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
	$url = substr($url, 1);
	$url = preg_replace('/(https|http):\//', '$1://', $url);

	//验证请求是否合法
	$white = json_decode(file_get_contents(CONFIG . 'white.json'), true);
	$matched = false;
	$verify = false;
	$replace = false;
	foreach ($white as $item) {
		if (preg_match($item['pattern'], $url)) {
			$matched = true;
			$verify = $item['verify'];
			$replace = $item['replace'];
			$cache_url = $item['static'];
			break;
		}
	}
	if (empty($matched)) {
		header('404 Not Found');
		die("<h2>Only whitelisted links are allowed</h2>");
	}

	//根据请求获取MIME
	$mimes = json_decode(file_get_contents(CONFIG . 'mime-lite.json'), true);
	$ext = explode(".", $url);
	$ext = $ext[count($ext) - 1];
	$ext = '.' . $ext;
	if (empty($mimes[$ext])) {
		$ext = '.html';
	}
	$mime = $mimes[$ext];

	//缓存文件，一周更新一次
	$cache_file = CACHE . md5($url) . $ext;
	if (!is_file($cache_file)) {
		$will_refrech = true;
	} elseif (time() - filemtime($cache_file) > 86400 * 7) {
		$will_refrech = true;
	} else {
		$will_refrech = false;
	}
	if ($will_refrech) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 900);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		$body = curl_exec($ch) or die("CURL Error:" . curl_error($ch));
		curl_close($ch);
		if (empty($verify) || preg_match($verify, $body)) {
			file_put_contents($cache_file, $body);
		}
	}

	//输出结果
	if (is_file($cache_file)) {
		header("Content-Type: ${mime}");
		header("Last-Modified:" . gmdate("D, d M Y H:i:s", filemtime($cache_file)) . " GMT");
		$body = file_get_contents($cache_file);
		if (is_array($replace)) {
			foreach ($replace as $key => $val) {
				$body = str_replace($key, $val, $body);
			}
			$body = str_replace('__PROXY__', PROXY, $body);
		}
		if (empty($cache_url)) {
			echo $body;
		} else {
			file_put_contents($cache_url, $body);
			header("Location: " . str_replace("proxy.php", $cache_url, $_SERVER['SCRIPT_NAME']));
		}
	} else {
		header('404 Not Found');
		die("<h2>Server Error!</h2>");
	}